package com.gem.taskplan.service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class SQLiteUtil {
	private SQLiteDatabase db = null;
	private String tableName = "users";


	public SQLiteUtil(SQLiteDatabase db) {
		super();
		this.db = db;
	}

	public void insert(String name, String birthday){
		String sql = "insert into "+tableName+" (name,pass) values(?,?)";
		Object args[] = new Object[]{name,birthday};
		db.execSQL(sql, args);
		db.close();
	}

	public String[] query(){
		String sql = "select name from users";
		System.out.println("333333333");
		Cursor cursor = db.rawQuery(sql, null);
		//System.out.println("4444444444");
		int count =0;

		for(cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext(),count++);

		String[] data = new String[count];
		cursor.moveToFirst();
		for(int i = 0;!cursor.isAfterLast();cursor.moveToNext(),i++){
			//System.out.println("555555555");
			//System.out.println(cursor.getString(0));
			data[i]= cursor.getString(0);
			System.out.println(data[i]);
		}
		db.close();
		return data;
	}

	public boolean check(String name){
		boolean flag =false;
		String sql = "select * from users where name = ?";
		String args[] = new String[]{name};
		Cursor cursor = db.rawQuery(sql, args);
		if(!cursor.isAfterLast()){
			flag =true;
		}
		db.close();
		return flag;
	}
	public boolean delete(String name){
		boolean flag = false;
		String sql = "delete from users where name = ?";
		String args[] = new String[]{name};
		Cursor cursor = db.rawQuery(sql, args);
		if(!cursor.isAfterLast()){
			flag =true;
		}
		db.close();
		return flag;
	}


	//分页查询
	public List<Map<String, Object>> query(int pageCode ,int pageSize){
		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();

		String sql = "select id,name,pass from "+tableName +"  limit ?,?";
		String aegs[] = new String[]{String.valueOf((pageCode-1)*pageSize),String.valueOf(pageSize)};
		Cursor cursor = db.rawQuery(sql, aegs);
		for(cursor.moveToFirst() ; !cursor.isAfterLast() ; cursor.moveToNext()){
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("id", cursor.getInt(0));
			map.put("name", cursor.getString(1));
			map.put("birthday", cursor.getString(2));
			list.add(map);
		}
		db.close();
		return list;
	}
}
